package com.hongtech.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongtech.common.bean.AjaxResultVo;
import com.hongtech.common.page.PageData;
import com.hongtech.framework.anno.Permission;
import com.hongtech.modules.common.BaseController;
import com.hongtech.modules.system.dto.SysLogDTO;
import com.hongtech.modules.system.entity.SysLogEntity;
import com.hongtech.modules.system.service.SysLogService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 日志控制器
 */
@Controller
@RequestMapping("/system/syslog")
public class LogController extends BaseController {

	@Autowired
	private SysLogService sysLogService;

	/**
	 * 跳转日志页
	 */
	@Permission("system:syslog:list")
	@RequestMapping("/list")
	public String listLog() {
		return "system/log/list";
	}

	/**
	 * 分页查询日志
	 */
	@Permission("system:syslog:list")
	@RequestMapping("/page")
	@ResponseBody
	public AjaxResultVo page(String search, String dateRange, Integer offset, Integer limit) {
		LambdaQueryWrapper<SysLogEntity> ew = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(search)) {
			ew.like(SysLogEntity::getTitle, search);
		}
		if (StringUtils.isNotBlank(dateRange)) {
			String[] dateRanges = StringUtils.split(dateRange, "~");
			ew.between(SysLogEntity::getCreateTime, dateRanges[0], dateRanges[1]);
		}
		ew.orderByDesc(SysLogEntity::getCreateTime);
		Map<String, Object> pageParams = getPageParam(limit, offset);
		PageData<SysLogDTO> pages = sysLogService.pages(pageParams, ew);
		AjaxResultVo resultVo = AjaxResultVo.success();
		resultVo.put("total", pages.getTotal());
		resultVo.put("rows", pages.getList());
		return resultVo;
	}

	/**
	 * 获取参数
	 */
	@Permission("system:syslog:list")
	@RequestMapping("/params/{id}")
	@ResponseBody
	public String params(@PathVariable Long id) {
		SysLogDTO sysLogDTO = sysLogService.get(id);
		return sysLogDTO.getParams();
	}

	/**
	 * 批量删除日志
	 *
	 * @param ids 集合
	 */
	@Permission("system:syslog:remove")
	@RequestMapping("/deleteBatch")
	@ResponseBody
	public AjaxResultVo deleteBatch(@RequestParam("id[]") List<Long> ids) {
		if (ObjectUtils.isEmpty(ids)) {
			return AjaxResultVo.error("参数错误");
		}
		if (sysLogService.delete(ids) > 0) {
			return AjaxResultVo.success();
		} else {
			return AjaxResultVo.error();
		}
	}

}
